﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace NinjaToolbox.SubComponentModule
{
    public abstract class SubComponentModelEditorBase
    {
        protected string mTitleName;
        protected SubComponentModelBase mTarget;

        SubComponentModelEditorData mEditorData;
        public SubComponentModelEditorData EditorData { get { return mEditorData; } }


        public virtual void Initialization(string titleName, SubComponentModelBase target)
        {
            mTitleName = titleName;
            mTarget = target;

            if (mTarget.UserData.GetUserData(SubComponentModelEditorData.KEY) == null)
                mTarget.UserData.AddUserData(SubComponentModelEditorData.KEY, new SubComponentModelEditorData());

            mEditorData = mTarget.UserData.GetUserData(SubComponentModelEditorData.KEY) as SubComponentModelEditorData;
        }

        public virtual float GetFinalHeight()
        {
            return mEditorData.IsUnfold ? 24f + GetInspectorGUIHeight() : 24f;
        }

        public virtual void OnGUI(Rect rect)
        {
            var headerIsClicked = false;
            var enableButtonClicked = false;

            SubComponentEditorUtil.DrawHeader(new Rect(rect.x, rect.y, rect.width, 23f), mTitleName, mTarget.Enabled, out headerIsClicked, out enableButtonClicked);

            if (headerIsClicked) mEditorData.IsUnfold = !mEditorData.IsUnfold;
            if (enableButtonClicked)
            {
                mTarget.Enabled = !mTarget.Enabled;
                GUI.changed = true;
            }

            if (mEditorData.IsUnfold)
            {
                EditorGUI.indentLevel++;

                EditorGUI.DrawRect(new Rect(rect.x, rect.y + 18f, rect.width, rect.height - 21f), new Color(0.8f, 0.8f, 0.8f, 1f));

                using (new EditorGUI.DisabledGroupScope(!mTarget.Enabled))
                {
                    OnInspectorGUI(new Rect(rect.x, rect.y + 24, rect.width, 20f));
                }

                EditorGUI.indentLevel--;
            }
        }

        protected abstract float GetInspectorGUIHeight();

        protected abstract void OnInspectorGUI(Rect rect);
    }
}
